<?php

namespace Admin\Controller;

use Admin\Controller\IndexController;
use Zend\Form\Annotation\AnnotationBuilder;
use Admin\Form\NewArticleForm;
use Admin\Entity\Article;
use Admin\Model\DBO\ArticleDBO;

class ArticleManagementController extends IndexController {

    public $userTable;
    public $form;

    public function getForm() {
        if (!$this->form) {
            $newArticle = new NewArticleForm();
            $builder = new AnnotationBuilder();
            $this->form = $builder->createForm($newArticle);
            $valueOptions = array(
                'news' => array(
                    'label' => 'Tin tức',
                    'options' => array(
                        '1' => 'Tin tức',
                        '2' => 'Thông báo',
                    ),
                ),
                'introduction' => array(
                    'label' => 'Giới thiệu',
                    'options' => array(
                        '3' => 'Sứ mệnh, chức năng và nhiệm vụ',
                        '4' => 'Cơ cấu tổ chức',
                        '5' => 'Tài nguyên',
                        '6' => 'Nộ quy',
                    ),
                ),
                'gallery' => array(
                    'label' => 'Hình ảnh hoạt động',
                    'options' => array(
                        '7' => 'Thư viện truyền thống',
                        '8' => 'Thư viện điện tử',
                    ),
                ),
                'manual' => array(
                    'label' => 'Hướng dẫn sử dụng',
                    'options' => array(
                        '9' => 'Thư viện điện tử',
                        '10' => 'Thư viện truyền thống',
                    ),
                ),
            );
            $this->form->get('subCategoryID')->setOptions(
                    array(
                        'value_options' => $valueOptions,
                    )
            );
        }

        return $this->form;
    }

    public function indexAction() {
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        // Chi co admin moi vao duoc quyen nay
        $this->checkRole1();
        // Neu dang nhap roi thi hien thi len sach sach nguoi dung
        // Lay thuc the dang nhap dua ra layout
        $this->layout()->identity = $this->getAuthService()->getIdentity();
        $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
        $paginator = $objectArticleDBO->fetchAll();
        $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
        $paginator->setItemCountPerPage(5);
        $paginator->setPageRange(3);

        return array(
            'paginator' => $paginator,
        );
    }

    public function newArticleAction() {
        // bắt đầu thêm bài viết

        $form = $this->getForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $myMessage = array();
            $nonFile = $request->getPost()->toArray();
            $File = $this->params()->fromFiles('pictureThumnail');
            $fileRename = "";
            $dirUpload = "";
            if (isset($File['name']) && $File['name'] != null) {
                $toArrayFileName = explode('.', $File['name']);
                $fileType = end($toArrayFileName);
                $fileRename = time() . '.' . $fileType;
                $dirUpload = getcwd() . '/public/img/gallery/thumnail';
                $data = array_merge(
                        $nonFile, array('fileupload' => $File['name'])
                );
                $form->setData($data);
            } else {
                $form->setData($nonFile);
            }
            if ($form->isValid()) {
                $data = $form->getData();
                $objectArticle = new Article();
                $objectArticle->exchangeArray($data);
                if (isset($File['name']) && $File['name'] != null) {
                    $objectArticle->setPictureThumnail('/img/gallery/thumnail/' . $fileRename);
                }
                $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
                if ($objectArticleDBO->saveArticle($objectArticle)) {
                    if (isset($File['name']) && $File['name'] != null) {
                        $objectUpload = new UploadImage();
                        $objectUpload->upload($File, $form, $dirUpload, $fileRename);
                    }
                    return $this->redirect()->toRoute('article-management');
                } else {
                    $myMessage['saveError'] = 'saveError';
                }
            } else {
                // Dua cac message error ra view
                foreach ($form->getMessages() as $value => $ms) {
                    $myMessage[$value] = $value;
                    var_dump($myMessage);
                    //  die;
                }
            }
            return array(
                'form' => $form,
                'myMessage' => $myMessage,
            );
        }
        return array(
            'form' => $form,
        );
    }

    public function editArticleAction() {
        $articleID = (int) $this->params()->fromRoute('id', 0);
        if (!$articleID) {
            return $this->redirect()->toRoute('article-management');
        }
        $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
        $article = new Article();
        $article->exchangeArray($objectArticleDBO->getArticle($articleID));
        $form = $this->getForm();
        $form->bind($article);
        $form->get('addNew')->setAttribute('value', 'Chỉnh sửa');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $nonFile = $request->getPost()->toArray();
            $File = $this->params()->fromFiles('pictureThumnail');
            $fileRename = "";
            $dirUpload = "";
            if (isset($File['name']) && $File['name'] != null) {
                $toArrayFileName = explode('.', $File['name']);
                $fileType = end($toArrayFileName);
                $fileRename = time() . '.' . $fileType;
                $dirUpload = getcwd() . '/public/img/gallery/thumnail';
                $data = array_merge(
                        $nonFile, array('fileupload' => $File['name'])
                );
                $form->setData($data);
            } else {
                $form->setData($nonFile);
            }
            if ($form->isValid()) {
                if (isset($File['name']) && $File['name'] != null) {
                    $article->setPictureThumnail('/img/gallery/thumnail/' . $fileRename);
                }
                if ($objectArticleDBO->updateArticle($article, $articleID)) {
                    if (isset($File['name']) && $File['name'] != null) {
                        $objectUpload = new UploadImage();
                        $objectUpload->upload($File, $form, $dirUpload, $fileRename);
                    }
                }
                // Redirect to list of rooms
                return $this->redirect()->toRoute('article-management');
            }
        }
        return array(
            'articleID' => $articleID,
            'form' => $form,
        );
    }

    public function deleteArticleAction() {
        $articleID = $this->params()->fromRoute('id', 0);
        $articleID = (int) $articleID;
        if ($articleID != 0) {
            $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
            $objectArticleDBO->deleteArticle($articleID);
        }
        return $this->redirect()->toRoute('article-management');
    }

    public function publishArticleAction() {
        $articleID = $this->params()->fromRoute('id', 0);
        $articleID = (int) $articleID;
        if ($articleID != 0) {
            $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
            $objectArticleDBO->changeStatusPublishArticle($articleID, 1);
        }
        return $this->redirect()->toRoute('article-management');
    }

    public function unPublishArticleAction() {
        $articleID = $this->params()->fromRoute('id', 0);
        $articleID = (int) $articleID;
        if ($articleID != 0) {
            $objectArticleDBO = new ArticleDBO($this->getServiceLocator());
            $objectArticleDBO->changeStatusPublishArticle($articleID, 0);
        }
        return $this->redirect()->toRoute('article-management');
    }

}

